package day1.linkedlist;

/**
 * @author pacai
 * @version 1.0
 */
@SuppressWarnings("all")
public class AddTwoNumbers {

    private static class Node{
        private int val;
        private Node next;

        public Node(int val) {
            this.val = val;
        }
    }


    //处理两条链表的相加
    public static Node addTwoNumbers(Node l1, Node l2) {
        int len1 = listLength(l1);
        int len2 = listLength(l2);
        Node l = len1 > len2 ? l1 : l2;
        Node s = l == l1 ? l2 : l1;
        Node curL = l;
        Node curS = s; // todo 较短链表最终没有返回，也可以直接使用它来遍历
        Node last = curL;
        int carry = 0; //进位
        int curNum = 0;//每一位上的相加数

        //计算较短链表+较长链表+进位
        while(curS != null){
            curNum = curS.val + curL.val + carry;
            curS.val = curNum % 10;
            carry = curNum / 10;
            last = curL;
            curL = curL.next;
            curS = curS.next;
        }

        //计算较长链表+进位
        while(curL != null){
            curNum = curL.val + carry;
            curL.val = curNum % 10;
            carry = curNum / 10;
            last = curL;
            curL = curL.next;
        }

        if(carry > 0){
            last.next = new Node(1);
        }
        return l;
    }

    //求链表长度
    public static int listLength(Node head){
        int len = 0;
        while(head != null){
            head = head.next;
            len++;
        }
        return len;
    }

    //返回链表的整数值
    public static int getLinkedListNum(Node head){
        String num = "";
        while(head != null){
            num += head.val;
            head = head.next;
        }
        return Integer.parseInt(num);
    }

}
